use std::convert::From;
use std::convert::{TryFrom, TryInto};
use std::fmt;
use std::string::ToString;

#[derive(Debug)]
struct Number {
    value: i32,
}

impl From<i32> for Number {
    fn from(item: i32) -> Self {
        Number { value: item }
    }
}

#[derive(Debug, PartialEq)]
struct EvenNumber(i32);

impl TryFrom<i32> for EvenNumber {
    type Error = ();
    fn try_from(value: i32) -> Result<Self, Self::Error> {
        if value % 2 == 0 {
            Ok(EvenNumber(value))
        } else {
            Err(())
        }
    }
}
// ToString FromStr
struct Circle {
    radius: i32,
}
impl fmt::Display for Circle {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Circle of radius {}", self.radius)
    }
}
//
fn main() {
    //类型转换
    //from
    // str -> String
    let my_str = "Hello";
    let my_string = String::from(my_str);

    //自定义from
    let n = Number::from(10);
    println!("{:#?}", n);

    //into
    let i = 5;
    let num: Number = i.into();
    println!("{:#?}", num);

    //try from 和try into

    match EvenNumber::try_from(10) {
        Ok(even_number) => println!("{:#?}", even_number),
        Err(_) => println!("Odd number"),
    }

    let res: EvenNumber = 8.try_into().unwrap();
    println!("8 {:#?}", res);

    // let res: EvenNumber = 1.try_into().unwrap();
    // println!("1 {:#?}", res);

    //ToString
    let circle = Circle { radius: 5 };
    println!("{:?}", circle.to_string());

    //FromStr 常用于讲字符串转换为其他类型

    let parsed: i32 = "44".parse().unwrap();
    println!("{}", parsed);
    let tup = "10".parse::<i32>().unwrap();
    println!("{}", tup);

    let sum = parsed + tup;
    println!("{}", sum);
}
